package cn.fldong.controller;

import cn.fldong.model.User;
import cn.fldong.service.UserService;
import cn.fldong.service.impl.UserServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;

/**
 * 用户管理Servlet，处理用户登录、注册等操作
 */
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String action = request.getParameter("action");

        if (action == null) {
            action = "loginForm";
        }

        try {
            switch (action) {
                case "login":
                    login(request, response);
                    break;
                case "register":
                    register(request, response);
                    break;
                case "logout":
                    logout(request, response);
                    break;
                case "loginForm":
                    request.getRequestDispatcher("/login.jsp").forward(request, response);
                    break;
                case "registerForm":
                    request.getRequestDispatcher("/register.jsp").forward(request, response);
                    break;
                default:
                    request.getRequestDispatcher("/login.jsp").forward(request, response);
                    break;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("errorMsg", "数据库操作异常: " + e.getMessage());
            request.getRequestDispatcher("/error.jsp").forward(request, response);
        }
    }

    /**
     * 用户登录
     */
    private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String remember = request.getParameter("remember");

        // 调用业务层进行登录验证
        User user = userService.login(username, password);

        if (user != null && "active".equals(user.getStatus())) {
            // 登录成功，将用户信息存入session
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            
            // 如果选择记住密码，可以在这里设置cookie（简化处理）
            if ("on".equals(remember)) {
                // 设置session有效期为7天
                session.setMaxInactiveInterval(7 * 24 * 60 * 60);
            }
            
            // 登录成功后跳转到首页
            response.sendRedirect(request.getContextPath() + "/index.jsp");
        } else {
            response.sendRedirect(request.getContextPath() + "/error.jsp");
        }
    }

    /**
     * 用户注册
     */
    private void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("confirmPassword");
        String fullName = request.getParameter("fullName");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");

        // 简单的表单验证
        if (username == null || username.isEmpty() || password == null || password.isEmpty()) {
            request.setAttribute("errorMsg", "用户名和密码不能为空");
            request.getRequestDispatcher("/register.jsp").forward(request, response);
            return;
        }

        if (!password.equals(confirmPassword)) {
            request.setAttribute("errorMsg", "两次输入的密码不一致");
            request.getRequestDispatcher("/register.jsp").forward(request, response);
            return;
        }

        // 检查用户名是否已存在
        if (userService.usernameExists(username)) {
            request.setAttribute("errorMsg", "用户名已存在，请选择其他用户名");
            request.getRequestDispatcher("/register.jsp").forward(request, response);
            return;
        }

        // 创建新用户
        User user = new User();
        user.setUsername(username);
        user.setPassword(password); // 实际项目中应该进行密码加密
        user.setFullName(fullName);
        user.setEmail(email);
        user.setPhone(phone);
        user.setRole("student"); // 默认角色为学生
        user.setStatus("active"); // 默认状态为激活
        user.setCreatedAt(new java.sql.Timestamp(new Date().getTime()));
        user.setUpdatedAt(new java.sql.Timestamp(new Date().getTime()));

        // 保存用户到数据库
        boolean success = userService.addUser(user);

        if (success) {
            // 注册成功，跳转到登录页面
            request.setAttribute("successMsg", "注册成功，请登录");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        } else {
            // 注册失败
            request.setAttribute("errorMsg", "注册失败，请稍后重试");
            request.getRequestDispatcher("/register.jsp").forward(request, response);
        }
    }

    /**
     * 用户退出登录
     */
    private void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        session.invalidate(); // 销毁session
        response.sendRedirect(request.getContextPath() + "/login.jsp");
    }
}